package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.album.TrackStat;
import com.atguigu.tingshu.query.album.TrackInfoQuery;
import com.atguigu.tingshu.vo.album.TrackInfoVo;
import com.atguigu.tingshu.vo.album.TrackListVo;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class TrackInfoServiceImpl extends ServiceImpl<TrackInfoMapper, TrackInfo> implements TrackInfoService {


	@Autowired
	private TrackInfoMapper trackInfoMapper;

	@Autowired
	private VodConstantProperties props;

	@Autowired
	private AlbumInfoMapper albumInfoMapper;

	@Autowired
	private VodService vodService;

	@Autowired
	private TrackStatMapper trackStatMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveTrackInfo(Long userId, TrackInfoVo trackInfoVo) {

		//1. 保存TrackInfo对象
		TrackInfo trackInfo = BeanUtil.copyProperties(trackInfoVo, TrackInfo.class);

		trackInfo.setUserId(userId);
//		// 先查专辑表，获取专辑中声音有多少条，然后加1
//		Long aLong = trackInfoMapper.selectCount(new LambdaQueryWrapper<TrackInfo>().eq(TrackInfo::getAlbumId, trackInfoVo.getAlbumId()));
//		// long类型转int类型 再加一
//		trackInfo.setOrderNum(aLong.intValue() + 1);

		AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfoVo.getAlbumId());
		trackInfo.setOrderNum(albumInfo.getIncludeTrackCount() + 1);

		trackInfo.setSource("1");// 按理说不是 1  但是表里都是1
		trackInfo.setStatus(SystemConstant.TRACK_STATUS_PASS);

		//1.4 根据文件唯一标识远程调用腾讯点播平台接口获取音频文件信息（音频时长、大小、音频类型）
		TrackMediaInfoVo trackMediaInfoVo = vodService.getTrackMediaInfo(trackInfoVo.getMediaFileId());
		if (trackMediaInfoVo != null) {
			trackInfo.setMediaDuration(new BigDecimal(trackMediaInfoVo.getDuration()));
			trackInfo.setMediaSize(trackMediaInfoVo.getSize());
			trackInfo.setMediaType(trackMediaInfoVo.getType());
		}

		trackInfoMapper.insert(trackInfo);
		Long trackId = trackInfo.getId();

		//2. 保存声音统计信息
		this.saveTrackStat(trackId, SystemConstant.TRACK_STAT_PLAY, 0);
		this.saveTrackStat(trackId, SystemConstant.TRACK_STAT_COLLECT, 0);
		this.saveTrackStat(trackId, SystemConstant.TRACK_STAT_PRAISE, 0);
		this.saveTrackStat(trackId, SystemConstant.TRACK_STAT_COMMENT, 0);


		//3. 保存专辑表中的声音数量信息
		albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount()+1);
		albumInfoMapper.updateById(albumInfo);

	}

	/**
	 * 根据条件分页查询用户的声音列表
	 * @param pageInfo 分页对象
	 * @param trackInfoQuery 查询条件对象
	 * @return
	 */
	@Override
	public Page<TrackListVo> getUserTrackByPage(Page<TrackListVo> pageInfo, TrackInfoQuery trackInfoQuery) {
		return trackInfoMapper.getUserTrackByPage(pageInfo, trackInfoQuery);
	}


	public void saveTrackStat(Long trackId, String statType, int statNum) {
		TrackStat trackStat = new TrackStat();
		trackStat.setTrackId(trackId);
		trackStat.setStatType(statType);
		trackStat.setStatNum(statNum);
		trackStatMapper.insert(trackStat);
	}


	/**
	 * 修改声音
	 *
	 * @param id          声音ID
	 * @param trackInfoVo 声音VO对象
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateTrackInfo(Long id, TrackInfoVo trackInfoVo) {
		//1.根据声音ID查询声音对象-判断声音是否变更
		TrackInfo trackInfo = trackInfoMapper.selectById(id);
		//1.2 变更前音频文件唯一标识
		String mediaFileIdBefore = trackInfo.getMediaFileId();
		//1.1 最新提交音频文件唯一标识
		String mediaFileIdAfter = trackInfoVo.getMediaFileId();
		//1.2 拷贝属性
		BeanUtil.copyProperties(trackInfoVo, trackInfo);

		//2.如果声音变更，获取最新声音相关音频信息（时长、大小、类型）为PO对象赋值
		if (!mediaFileIdBefore.equals(mediaFileIdAfter)) {
			TrackMediaInfoVo trackMediaInfo = vodService.getTrackMediaInfo(mediaFileIdAfter);
			if(trackMediaInfo!=null){
				trackInfo.setMediaType(trackMediaInfo.getType());
				trackInfo.setMediaDuration(BigDecimal.valueOf(trackMediaInfo.getDuration()));
				trackInfo.setMediaSize(trackMediaInfo.getSize());
				//4.将变更前声音文件从云点播平台删除
				vodService.deleteTrackMedia(mediaFileIdBefore);
			}
		}
		//3.更新声音
		trackInfoMapper.updateById(trackInfo);
	}

	/**
	 * 根据ID删除声音
	 * @param id 声音ID
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void removeTrackInfo(Long id) {
		//1.根据要删除声音ID查询声音对象-获取当前声音序号用于更新其他声音序号
		TrackInfo trackInfo = trackInfoMapper.selectById(id);
		Integer orderNum = trackInfo.getOrderNum();
		//2.删除声音-逻辑删除
		trackInfoMapper.deleteById(id);

		//3.将比删除声音序号大的声音序号进行递减
		trackInfoMapper.updateTrackNum(trackInfo.getAlbumId(), orderNum);

		//4.删除声音统计记录
		LambdaQueryWrapper<TrackStat> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(TrackStat::getTrackId, id);
		trackStatMapper.delete(queryWrapper);

		//5.更新专辑包含声音数量减一
		AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfo.getAlbumId());
		albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount()-1);
		albumInfoMapper.updateById(albumInfo);

		//6.删除云点播平台声音文件
		vodService.deleteTrackMedia(trackInfo.getMediaFileId());
	}
}
